package top.callback.inf.beautyleaf.common.utils;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import top.callback.inf.beautyleaf.segment.dao.LeafTagMapper;

import javax.sql.DataSource;


/**
 * Mybatis 辅助工具，负责创建 {@link SqlSessionFactory}
 *
 * @author Pengyu Gan
 * CreateDate 2021/3/23
 */
public class MybatisHelper {

    private SqlSessionFactory sqlSessionFactory;

    /**
     * 使用默认连接池配置的数据源初始化
     * @param driver 数据库驱动
     * @param url 数据库连接字符串
     * @param username 数据库用户名
     * @param password 数据库密码
     */
    public MybatisHelper(String driver, String url, String username, String password) {
        // 配置数据源
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        // 连接池配置
        dataSource.setMaxLifetime(180000);
        dataSource.setIdleTimeout(30000);
        dataSource.setMinimumIdle(1);
        dataSource.setMaximumPoolSize(20);
        dataSource.setConnectionTestQuery("SELECT 1");
        init(dataSource);
    }

    /**
     * 使用指定的数据源初始化
     * @param dataSource 数据源
     */
    public MybatisHelper(DataSource dataSource) {
        init(dataSource);
    }

    public void init(DataSource dataSource) {
        // Mybatis 配置
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        // 加载 Mapper
        configuration.addMapper(LeafTagMapper.class);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    }

    public SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}
